window.addEventListener("message", function(event){
	var data = event.data;
	if(event.source != window){
		return;
	}
	if(data.sender && data.sender == "PAGE"){
		if(data.type && data.type == "get_list"){
			chrome.storage.sync.get(data.list_name,function(obj){
				if(obj[data.list_name] && obj[data.list_name].value && obj[data.list_name].value != ""){
					window.postMessage({sender: "EXTENSION", type: "callback",callback:data.callback,response:true}, document.location.origin);
				}
				else{
					chrome.runtime.sendMessage({action:"get_list",list:data.list_name},function(resp){
						if(resp){
							window.postMessage({sender: "EXTENSION", type: "callback",callback:data.callback,response:true}, document.location.origin);
						}
						else{
							window.postMessage({sender: "EXTENSION", type: "callback",callback:data.callback,response:false}, document.location.origin);
						}
					})
				}
			});
		}
		//MW App ID is hardcoded here, but easily adaptable if needed for some reason in future
		if(data.type && data.type == "load_posts"){
			chrome.runtime.sendMessage({action:"load_posts",list:data.list_name,amount:data.amount,time:data.time,appid:10979261223},function(resp){
				window.postMessage({sender: "EXTENSION", type: "callback",callback:data.callback,response:resp}, document.location.origin);
			});
		}
		if(data.type && data.type == "load_more_posts"){
			chrome.runtime.sendMessage({action:"load_posts",amount:data.amount,time:data.time,appid:10979261223,link:data.link},function(resp){
				window.postMessage({sender: "EXTENSION", type: "callback",callback:data.callback,response:resp}, document.location.origin);
			});
		}
	}

}, false);

//Add a footprint to the page for easy checking if the extension exists. 
var script = document.createElement("script"); 
script.innerHTML = "var spockholm_feed_api = true;"; 
document.head.appendChild(script);
